package com.sdt.security04.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author : fujc-dev@qq.com
 * @created : 2022/10/24 11:17
 */
@Configuration
//@EnableWebSecurity 在SpringBoot中可以不加，为什么呢？因为WebSecurityEnablerConfiguration已经开启了
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService myUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //AuthenticationManagerBuilder 这里面有很多属性与方法：
        //可以看到UserDetailsService defaultUserDetailsService这个属性，这里面还是可以写入一个UserDetailsService.
        // auth.inMemoryAuthentication()
        //         .withUser("fox")
        //         .password(passwordEncoder().encode("123456"))
        //         .authorities("admin")
        //         .and()
        //         // 这个and的意思就是再来一次
        //         .withUser("fujc")
        //         .password(passwordEncoder().encode("123456"))
        //         .authorities("admin");
        auth.userDetailsService(myUserDetailsService);

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

//    @Bean
//    @Override
//    public UserDetailsService userDetailsServiceBean() throws Exception {
//        return new MyUserDetailsServiceImpl();
//    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()  //表达登录
                .loginPage("/login.html") //指定登录路径
                .loginProcessingUrl("/user/login")  // 对应 action="/user/login"
                .defaultSuccessUrl("/main.html");
        //.failureHandler()

        //授权
        http.authorizeRequests()
                // 不用认证
                .antMatchers("/login.html", "/user/login").permitAll()
                .anyRequest().authenticated();  //认证
        //默认开启跨站伪造保护
        http.csrf().disable();
    }
}
